package com.itheima.reggie.service.Impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    //调用EmployeeMapper 进行查询
    @Autowired
    private EmployeeMapper employeeMapper;

    //添加方法
    @Override
    public void save(Employee employee) {
        //将除了添加的五个之外的值初始化
        //添加id雪花算法 生成唯一数值
        employee.setId(IdUtil.getSnowflake(1,1).nextId());
        //密码先进行加密
        String md5 = SecureUtil.md5(Constant.INIT_PASSWORD);
        employee.setPassword(md5);
        //设置sates进入默认激活状态
        employee.setStatus(Employee.STATUS_ENABLE);
        //两个时间初始化
//        employee.setCreateTime(new Date());
//        employee.setUpdateTime(new Date());
        //两个修改人激活
//        employee.setCreateUser(1L);
//        employee.setUpdateUser(1L);
        //调用mapper save 方法
        employeeMapper.save(employee);
    }
    //通过id查找对象
    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);
    }
    //更新方法
    @Override
    public void update(Employee employee) {
        //初始化修改时间 和人
        //1. 设置两个字段
//        employee.setUpdateTime(new Date());
//        employee.setUpdateUser(1L);//临时写死
        employeeMapper.update(employee);
    }

    @Override
    public ResultInfo login(String username, String password) {
        //调用查询方法
        Employee employee=employeeMapper.findByName(username);
        //判断用户名是否为空
        if(employee==null){
            return ResultInfo.error("当前用户名为空");
        }
        //将密码进行解密
        String passwordMd5 = SecureUtil.md5(password);
        //通过名字得到密码 并和解密后的密码进行比较
        String passwordBd = employee.getPassword();
        if (!StringUtils.equals(passwordMd5,passwordBd)){
            return ResultInfo.error("密码错误");
        }
        //判断用户是否处于激活状态
        if(employee.getStatus()!=employee.STATUS_ENABLE){
            return ResultInfo.error("用户未被激活");
        }
        //若以上信息都不符合 返回成功
        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> findName(String name) {
        List<Employee> employeeList = employeeMapper.findName(name);
        return employeeList;
    }
}
